<template>
  <el-container class="admin-layout">
    <el-main>
      <el-card shadow="never">
        <template #header>
          <div class="card-header">
            <span>配送管理</span>
            <el-button type="primary" @click="handleOpenDialog()">添加配送</el-button>
          </div>
        </template>

        <div class="filter-container">
          <el-input
            v-model="searchQuery"
            placeholder="按当前地址或配送员电话搜索"
            clearable
            style="width: 300px;"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>

        <el-table :data="filteredDelivers" v-loading="loading" style="width: 100%" row-key="id" @expand-change="handleExpand">
          <el-table-column type="expand">
            <template #default="props">
              <div v-if="expandLoadingMap[props.row.id]" style="padding: 20px; text-align:center;">
                <el-spin />
              </div>
              <div v-else-if="detailMap[props.row.id]" class="expand-content">
                <el-descriptions title="订单与商品" size="small" :column="2" border>
                  <el-descriptions-item label="订单ID">{{ detailMap[props.row.id]?.order.id }}</el-descriptions-item>
                  <el-descriptions-item label="总金额">¥{{ detailMap[props.row.id]?.order.totalAmount.toFixed(2) }}</el-descriptions-item>
                  <el-descriptions-item label="商品名称">{{ detailMap[props.row.id]?.product.name }}</el-descriptions-item>
                  <el-descriptions-item label="订单状态">
                     <el-tag :type="detailMap[props.row.id]?.order.status === 'end' ? 'success' : 'info'">
                        {{ detailMap[props.row.id]?.order.status }}
                     </el-tag>
                  </el-descriptions-item>
                </el-descriptions>
                <el-descriptions title="用户信息" size="small" :column="2" border>
                  <el-descriptions-item label="昵称">{{ detailMap[props.row.id]?.user.name }}</el-descriptions-item>
                  <el-descriptions-item label="手机号">{{ detailMap[props.row.id]?.user.phoneNumber }}</el-descriptions-item>
                </el-descriptions>
                <el-descriptions title="地址信息" size="small" :column="2" border>
                  <el-descriptions-item label="收件人">{{ detailMap[props.row.id]?.address.receiverName }}</el-descriptions-item>
                  <el-descriptions-item label="电话">{{ detailMap[props.row.id]?.address.receiverPhone }}</el-descriptions-item>
                  <el-descriptions-item label="完整地址" :span="2">
                    {{ detailMap[props.row.id]?.address.country }} {{ detailMap[props.row.id]?.address.province }} {{ detailMap[props.row.id]?.address.county }} {{ detailMap[props.row.id]?.address.detailAddress }}
                  </el-descriptions-item>
                </el-descriptions>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="id" label="配送ID" />
          <el-table-column prop="orderId" label="订单ID" />
          <el-table-column prop="currentAddress" label="当前位置" />
          <el-table-column prop="delivererPhone" label="配送员电话" />
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button size="small" @click="handleOpenDialog(scope.row)">编辑</el-button>
              <el-popconfirm
                title="确定要删除这条配送信息吗?"
                confirm-button-text="确认"
                cancel-button-text="取消"
                @confirm="handleDelete(scope.row.id)"
              >
                <template #reference>
                  <el-button size="small" type="danger">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-main>
  </el-container>

  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px" @close="resetForm">
    <el-form :model="formDeliver" label-width="100px" ref="formRef" :rules="rules">
      <el-form-item label="订单" prop="orderId">
         <el-select v-model="formDeliver.orderId" placeholder="请选择订单" filterable style="width: 100%;" @change="handleOrderChange">
            <el-option v-for="o in allOrders" :key="o.id" :label="`订单ID: ${o.id}`" :value="o.id" />
          </el-select>
      </el-form-item>
      <el-form-item label="地址 ID" prop="addressId">
        <el-input v-model.number="formDeliver.addressId" :disabled="true" />
      </el-form-item>
      <el-form-item label="当前地址" prop="currentAddress">
        <el-input v-model="formDeliver.currentAddress" />
      </el-form-item>
      <el-form-item label="配送员电话" prop="delivererPhone">
        <el-input v-model="formDeliver.delivererPhone" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, reactive } from 'vue';
import apiClient from '../../axios/axios';
import { ElMessage, ElIcon, ElDescriptions, ElDescriptionsItem } from 'element-plus';
import { Search } from '@element-plus/icons-vue';
import type { FormInstance, FormRules } from 'element-plus';

// --- Interfaces ---
interface Deliver {
  id: number;
  orderId: number;
  addressId: number;
  currentAddress: string;
  delivererPhone: string;
}
interface Order { id: number; customerId: number; productId: number; addressId: number; status: string; totalAmount: number; orderDate: string; }
interface User { id: number; name: string; phoneNumber: string; }
interface Product { id: number; name: string; price: number; }
interface Address { id: number; userId: number; receiverName: string; receiverPhone: string; country: string; province: string; county: string; detailAddress: string; }
interface DeliverInfoResponse { deliver: Deliver; order: Order; user: User; address: Address; product: Product; }

// --- Component State ---
const allDelivers = ref<Deliver[]>([]);
const allOrders = ref<Order[]>([]);
const loading = ref(false);
const searchQuery = ref('');

// --- Table and Filter ---
const filteredDelivers = computed(() => {
  if (!searchQuery.value) return allDelivers.value;
  const query = searchQuery.value.toLowerCase();
  return allDelivers.value.filter(d =>
    d.currentAddress.toLowerCase().includes(query) ||
    d.delivererPhone.includes(query)
  );
});

// --- Data Fetching ---
const fetchDelivers = async () => {
  loading.value = true;
  try {
    const response = await apiClient.get<Deliver[]>('/delivers');
    allDelivers.value = response.data;
  } catch (error) {
    console.error("Failed to fetch delivers", error);
    ElMessage.error('获取配送列表失败');
  } finally {
    loading.value = false;
  }
};

const fetchOrders = async () => {
    try {
        const res = await apiClient.get<Order[]>('/orders');
        allOrders.value = res.data;
    } catch (err) {
        ElMessage.error('获取订单列表失败');
    }
}

onMounted(() => {
  fetchDelivers();
  fetchOrders();
});

// --- Expandable Row ---
const expandLoadingMap = ref<Record<number, boolean>>({});
const detailMap = ref<Record<number, DeliverInfoResponse>>({});

const handleExpand = async (row: Deliver, expandedRows: Deliver[]) => {
  if (!expandedRows.includes(row) || detailMap.value[row.id]) return;
  expandLoadingMap.value[row.id] = true;
  try {
    const res = await apiClient.get<DeliverInfoResponse>(`/delivers/${row.id}/info`);
    detailMap.value[row.id] = res.data;
  } catch (err) {
    console.error('获取配送详情失败', err);
    ElMessage.error('获取配送详情失败');
  } finally {
    expandLoadingMap.value[row.id] = false;
  }
};

// --- Dialog and Form ---
const dialogVisible = ref(false);
const dialogTitle = ref('');
const formRef = ref<FormInstance>();
const editingDeliverId = ref<number | null>(null);

const initialFormState: Omit<Deliver, 'id'> = {
  orderId: 0,
  addressId: 0,
  currentAddress: '',
  delivererPhone: '',
};
const formDeliver = reactive({ ...initialFormState });

const rules = reactive<FormRules>({
  orderId: [{ required: true, message: '请选择订单', trigger: 'change' }],
  currentAddress: [{ required: true, message: '请输入当前地址', trigger: 'blur' }],
  delivererPhone: [{ required: true, message: '请输入配送员电话', trigger: 'blur' }],
});

const handleOrderChange = (orderId: number) => {
    const selectedOrder = allOrders.value.find(o => o.id === orderId);
    if(selectedOrder) {
        formDeliver.addressId = selectedOrder.addressId;
    }
}

const resetForm = () => {
  Object.assign(formDeliver, initialFormState);
  editingDeliverId.value = null;
  formRef.value?.clearValidate();
};

const handleOpenDialog = (deliver?: Deliver) => {
  if (deliver) {
    dialogTitle.value = '编辑配送信息';
    editingDeliverId.value = deliver.id;
    Object.assign(formDeliver, deliver);
  } else {
    dialogTitle.value = '添加配送';
    resetForm();
  }
  dialogVisible.value = true;
};

const submitForm = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      try {
        if (editingDeliverId.value) {
          await apiClient.put(`/delivers/${editingDeliverId.value}`, formDeliver);
        } else {
          await apiClient.post('/delivers', formDeliver);
        }
        ElMessage.success(editingDeliverId.value ? '更新成功' : '添加成功');
        dialogVisible.value = false;
        fetchDelivers();
      } catch (error) {
        console.error('Failed to save deliver', error);
        ElMessage.error('操作失败');
      } finally {
        loading.value = false;
      }
    }
  });
};

const handleDelete = async (id: number) => {
  try {
    await apiClient.delete(`/delivers/${id}`);
    ElMessage.success('删除成功');
    fetchDelivers();
  } catch (error) {
    console.error('Failed to delete deliver', error);
    ElMessage.error('删除失败');
  }
};
</script>

<style scoped>
.admin-layout {
  height: 100%;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.filter-container {
  margin-bottom: 20px;
}
.expand-content .el-descriptions {
  margin-top: 10px;
}
.expand-content .el-descriptions:first-child {
  margin-top: 0;
}
</style> 